package net.oktaeder.office;

import java.io.File;

import net.oktaeder.office.view.filemailer.FileMailer;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Helper class for accessing configuration of the system
 * 
 * @author tuukka
 *
 */
public class ConfigurationHelper {

	private static Log log = LogFactory.getLog(FileMailer.class);
	private static ConfigurationHelper instance;
	XMLConfiguration config;
	
	/**
	 * Private constructor used to implement Singleton pattern
	 * Loads configuration
	 * 
	 * @throws Exception when something fails
	 */
	private ConfigurationHelper() throws Exception {
		String file;
		try {
			log.trace("Creating an instance");
			file = resolveConfigurationLocation();
			log.info("Config resolved to: " + file);
			config = new XMLConfiguration(file);			
		} catch (Exception ex) {
			log.fatal("Instance of configuration helper couldn't be created", ex);
			throw new Exception("Instance of configuration helper couldn't be created", ex);
		}
	}
	
	/**
	 * Method used to access the configuration of the system
	 * 
	 * @return initialized instance of Configuration
	 * @throws Exception when something fails
	 */
	public static Configuration getConfiguration() throws Exception {
		try {
			if (instance == null) {
				instance = new ConfigurationHelper();
			}
			return instance.config;			
		} catch (Exception ex) {
			log.fatal("Getting the configuration failed", ex);
			throw new Exception("Failed to get the configuration", ex);			
		}
	}
	
	/**
	 * Resolves name and possible path of the configuration file
	 * 
	 * @return name of the configuration file
	 */
	private String resolveConfigurationLocation() {
		String fileName;
		File file;
		
		fileName = "office-config.xml";
		file = new File(fileName);
		
		if (file.exists()) {
			return fileName;
		}
		
		log.info("Using development configuration");
		//TODO: clean up, since this code is awfully ugly
		fileName = "E:/programming/java/projects/nSpace/nspaceMain/office-config.xml";
		
		return fileName;
	}
	
}
